package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.support.rowset.SqlRowSet

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 微信小程序页面调用API*
 */

public class apiWXMiniSendSMS implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXMiniSendSMS.class);
    private static String gPoster_Guid = null;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        String WXCallBackURL = KHDBConfig.getAPIURL(eliteBean, "WXCallBackURL") + "/ngsapitask_pa/file/apiFileProxy?fileurl=" + KHDBConfig.getAPIURL(eliteBean, "NGS-InnserDomain") + "fs/get?file=";

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = request.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        //  入参为空
        if (KHUtil.isNull(inData)) {
            log.debug("入参为空-无法完成操作!");
            result.put("errcode", -2);
            result.put("errmsg", "入参为空-无法完成操作!");

            return result.toString();
        }

        try {
            String API_OuterDomain = KHDBConfig.getAPIURL(eliteBean, "API-InnerDomain");
            // 解析调用参数
            JSONObject inJson = JSONObject.fromObject(inData);
            String rolegroup_ID = inJson.getString("rolegroup_id");
            String staff_ID = inJson.getString("staff_id");
            String tempplate_ID = inJson.getString("tempplate_id");
            String poster_Guid = inJson.getString("poster_guid");
            String tempplate_Value = inJson.getString("tempplate_value");
            String tempplate_Param = inJson.getString("tempplate_param");
            gPoster_Guid = poster_Guid;

            // 将数据批量插入DocumentOUT
            String selectSQL = '''Select R2.Rec_Guid, R2.Mobile, R2.Doctemplate_Values, R1.Poster_Url, R1.Poster_Wechat_URL
                                      From Poster_Batch R1
                                      Left Join Poster_List R2
                                        On R1.Poster_Guid = R2.Batch_Guid
                                     Where R1.Poster_Guid = ?''';

            SqlRowSet selectRow = jt.queryForRowSet(selectSQL, poster_Guid);

            //移动光标，获取记录
            JSONObject postBody = new JSONObject();
            String Rec_Guid = "";
            String Mobile = "";
            String Poster_Url = "";
            String Poster_Wechat_URL = "";
            String url_link = "";

            String Documentpath = "";
            String Documentpath2 = "";

            int succNum = 0;
            int failNum = 0;

            dealToDB(jt, "发送中", poster_Guid);

            while (selectRow.next()) {
                Rec_Guid = selectRow.getString("Rec_Guid");
                Mobile = selectRow.getString("Mobile");
                Poster_Url = selectRow.getString("Poster_Url");
                Poster_Url = WXCallBackURL + Poster_Url;
                Poster_Wechat_URL = selectRow.getString("Poster_Wechat_URL");
                log.debug("编号: " + Rec_Guid + " 发送手机号码: " + Mobile + " 海报路径: " + Poster_Url + " 发送PAURL: " + Poster_Wechat_URL);

                if (KHUtil.isNull(Poster_Wechat_URL)) {
                    log.debug("批次平安短链为空,获取腾讯短链...");
                    int errcode = -1;
                    JSONObject postResultJson = null;
                    // 调用获取短链接
                    try {
                        postBody.clear();
                        postBody.put("path", "/pages/index/index");
                        postBody.put("is_expire", true);
                        postBody.put("expire_type", 1);
                        postBody.put("expire_interval", 30);

                        postBody.put("query", "recid=" + Rec_Guid + "&expand=3");

                        String postResult = Util.doHttpPost(API_OuterDomain + "/apiWXMiniPURL", postBody.toString(), "UTF-8", 12000, 0);

                        postResultJson = JSONObject.fromObject(postResult);

                        errcode = postResultJson.getInt("errcode");
                    } catch (Exception e) {
                        log.error("获取腾讯短链接失败", e);
                    }
                    if (errcode == 0) {
                        // 获取短链接成功
                        url_link = postResultJson.getString("url_link");
                        log.debug("获取腾讯短链接成功:" + url_link);
                    } else {
                        if (KHUtil.isURL(Poster_Wechat_URL)) {
                            url_link = Poster_Wechat_URL;
                            log.debug("获取腾讯短链接错误,使用平安短链:" + url_link);
                        } else {
                            url_link = "";
                            log.debug("获取腾讯短链接错误,使用平安短链,但平安短链也是空:" + Poster_Wechat_URL);
                        }
                    }
                } else {
                    log.debug("批次平安短链非空,检查平安短链:" + Poster_Wechat_URL);
                    if (KHUtil.isURL(Poster_Wechat_URL)) {
                        url_link = Poster_Wechat_URL;
                    } else {
                        url_link = "";
                    }
                    log.debug("批次平安短链非空,平安短链检查结果:" + url_link);
                }

                String MsgID = System.currentTimeMillis() +new Random().nextInt(99999).toString();
                if (!KHUtil.isNull(url_link)) {
                    // 获取短链接成功
                    Documentpath = tempplate_Value.replace("[\$" + tempplate_Param + "\$]", url_link);
                    Documentpath2 = "{\"" + tempplate_Param + "\":\"" + url_link + "\"}"

                    log.debug("短链接地址：" + url_link + " 短内容：" + Documentpath + " 参数内容：" + Documentpath2);

                    String insertSQL = '''Insert Into Documentout
                                              (Documentout_Guid,
                                               Doctype,
                                               Status,
                                               Trialcount,
                                               Trialcountlimit,
                                               Documentpath,
                                               Documentpath2,
                                               Handleby_Id,
                                               Handlegroup_Id,
                                               Customer_Guid,
                                               Createdby,
                                               Createddate,
                                               Expectedstartdate,
                                               Documentto,
                                               Lasttrydatetime,
                                               Sub_Doctype,
                                               Msgid,
                                               Template_Id,
                                               Poster_Guid,
                                               Poster_Url,
                                               Send_Type,
                                               Stringfield1)
                                            Values
                                              (?,
                                               3,
                                               0,
                                               0,
                                               3,
                                               ?,
                                               ?,
                                               ?,
                                               ?,
                                               Null,
                                               ?,
                                               Now(),
                                               Now(),
                                               ?,
                                               Null,
                                               '海报批量发送',
                                               ?,
                                               ?,
                                               ?,
                                               ?,
                                               '3',
                                               ?)''';

                    int insertNum = jt.update(insertSQL, Rec_Guid, Documentpath, Documentpath2, staff_ID, rolegroup_ID, staff_ID, Mobile, MsgID, tempplate_ID, poster_Guid, Poster_Url, Poster_Url);

                    log.debug("批量发送海报短信：" + Rec_Guid + " 成功 操作数据：" + insertNum);

                    succNum++;

                } else {
                    String errmsg = "当前批次配置的平安短链接地址非合法URL请检查";
                    String insertSQL = '''Insert Into Documentout
                                              (Documentout_Guid,
                                               Doctype,
                                               Status,
                                               Trialcount,
                                               Trialcountlimit,
                                               Documentpath,
                                               Documentpath2,
                                               Handleby_Id,
                                               Handlegroup_Id,
                                               Customer_Guid,
                                               Createdby,
                                               Createddate,
                                               Expectedstartdate,
                                               Documentto,
                                               Lasttrydatetime,
                                               Sub_Doctype,
                                               Msgid,
                                               Template_Id,
                                               Poster_Guid,
                                               Poster_Url,
                                               Send_Type,
                                               Failcode,
                                               Faildescription)
                                            Values
                                              (?,
                                               3,
                                               -1,
                                               0,
                                               3,
                                               ?,
                                               ?,
                                               ?,
                                               ?,
                                               Null,
                                               ?,
                                               Now(),
                                               Now(),
                                               ?,
                                               Null,
                                               '海报批量发送',
                                               ?,
                                               ?,
                                               ?,
                                               ?,
                                               '3',
                                               ?,
                                               ?)''';

                    jt.update(insertSQL, Rec_Guid, tempplate_Value, tempplate_Param, staff_ID, rolegroup_ID, staff_ID, Mobile, MsgID, tempplate_ID, poster_Guid, Poster_Url, -1, errmsg);
                    log.warn("批量发送海报短信：" + Rec_Guid + " 发送短链接失败：" + errmsg);
                    failNum++;
                }

            }
            dealToDB(jt, "已完成", gPoster_Guid);
            result.put("errcode", 1);
            result.put("errmsg", "成功[" + succNum + "]失败[" + failNum + "]");

        } catch (Exception e) {
            log.error("发送批量海报异常-", e);
            dealToDB(jt, "发送失败", gPoster_Guid);
            result.put("errcode", -1);
            result.put("errmsg", "数据处理错误[" + e.getMessage() + "]");
        }

        return result.toString();
    }

    // 状态控制更新到DB
    public static void dealToDB(JdbcTemplate jt, String Batch_State, String Poster_Guid) {

        // 状态控制更新到DB
        String dealSQL = "Update Poster_Batch Set Batch_State = ? Where Poster_Guid = ?";
        jt.update(dealSQL, Batch_State, Poster_Guid);
    }

}
